from tortoise.expressions import Q, F

from app.core.crud import CRUDBase
from app.models import Exam
from app.models.exams import Question
from app.schemas.exams import QuestionCreate, QuestionUpdate


class QuestionController(CRUDBase[Question, QuestionCreate, QuestionUpdate]):
    def __init__(self):
        super().__init__(model=Question)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs = await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at", "deleted_at","questions"]) for obj in objs]
        return total, data

    async def do_create(self, obj_in: QuestionCreate):
        ##查试卷是否存在
        exam_id = obj_in.exam_id
        exam_data = await Exam.filter(id=exam_id).first().values("id")
        if exam_data:
            ##试卷存在
            ret = await self.create(obj_in=obj_in)
            return ret
        else:
            return False

    async def do_update(self, obj_in: QuestionUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def do_detail(self, data_id: int):
        data = await Question.filter(exam_id=data_id).all().values("id", "question", "selects")
        ##1.
        # q = Q(exam_id=data_id)
        # total,questions = await question_controller.do_list(page=1,page_size=100,search=q)
        ##2.
        # questions = await Question.filter(exam_id=data_id).all().values("id", "question", "selects")
        return data

question_controller = QuestionController()
